import { message } from 'ant-design-vue';
import SparkMD5 from 'spark-md5';

export function copyToClipboard(text: any) {
  navigator.clipboard
    .writeText(text)
    .then(() => {
      message.success('复制成功');
    })
    .catch(() => {
      message.error('复制失败');
    });
}

// 保留两位小数
export function toFixed2(num: number) {
  return Number(num.toFixed(2));
}

// 金额转化为元
export function formatMoney(money: number) {
  return Number((money / 100).toFixed(2));
}
// 元转化为分
export function formatMoneyToCent(money: number) {
  return Number((money * 100).toFixed(0));
}
export function gotoAliiwanwan(name: string) {
  open(
    encodeURI(
      `https://air.1688.com/app/ocms-fusion-components-1688/def_cbu_web_im/index.html?touid=cnalichn${name}&siteid=cnalichn#/`,
    ),
  );
}

// 字符串相似度
export function similarity(s1: string, s2: string) {
  let i;
  let j;
  const lens1 = s1.length;
  const lens2 = s2.length;
  const matrix: any = [];
  let s1_i;
  let s2_j;

  if (!s1 || !s2) {
    return 0;
  }

  if (s1 === s2) {
    return 1;
  }

  for (i = 0; i <= lens1; i++) {
    matrix[i] = [i];
  }

  for (j = 0; j <= lens2; j++) {
    matrix[0][j] = j;
  }

  for (i = 1; i <= lens1; i++) {
    s1_i = s1[i - 1];

    for (j = 1; j <= lens2; j++) {
      s2_j = s2[j - 1];

      matrix[i][j] = Math.min(
        matrix[i - 1][j] + 1,
        matrix[i][j - 1] + 1,
        matrix[i - 1][j - 1] + (s1_i === s2_j ? 0 : 1),
      );
    }
  }

  return 1 - matrix[lens1][lens2] / Math.max(s1.length, s2.length);
}

// 获取文件到MD5
export function calculateFileMD5(file: any) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    const spark = new SparkMD5.ArrayBuffer();

    fileReader.addEventListener('load', (e: any) => {
      spark.append(e.target.result);
      resolve(spark.end());
    });

    // eslint-disable-next-line unicorn/prefer-add-event-listener
    fileReader.onerror = function (err) {
      reject(err);
    };

    // eslint-disable-next-line unicorn/prefer-blob-reading-methods
    fileReader.readAsArrayBuffer(file);
  });
}

// 获取url的bolb
export async function urlToBlob(url: string): Promise<Blob> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Failed to fetch image: ${response.statusText}`);
  }
  return response.blob();
}
